package com.coman404.mvc;

import com.coman404.mvc.conf.ControllerHandlerConf;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;

import java.util.Set;

/**
 * @author NotFound404 at 2024/6/3
 * code code always code
 */

@SpringBootApplication
public class AppRunner implements CommandLineRunner {

    @Autowired
    private ControllerHandler controllerHandler;


    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(AppRunner.class,args);
    }

    @Override
    public void run(String... args) throws Exception {
        HttpServer server = new HttpServer();
        server.start();
    }

    public class HttpServer{
        public void start(){
            EventLoopGroup boos = new NioEventLoopGroup();
            EventLoopGroup worker = new NioEventLoopGroup();
            ServerBootstrap serverBootstrap = null;
            try {
                serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(boos, worker)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) throws Exception {
                                ch.pipeline().addLast(new HttpServerCodec())
                                        .addLast(new ChunkedWriteHandler())
                                        .addLast(new HttpObjectAggregator(1024*1024))
                                        .addLast(controllerHandler);

                            }
                        });
                ChannelFuture cf = serverBootstrap.bind(8080).sync();
                cf.channel().closeFuture().sync();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                boos.shutdownGracefully();
                worker.shutdownGracefully();
            }
        }
    }

}
